const footer = `
if (import.meta.hot) {
  import.meta.hot.accept(newModel => {
    if (!newModel) {
      return
    }
    const model = newModel.default || newModel
    window.dvaApp.replaceModel(model)
  })
}`
function addRefreshWrapper(code) {
  return code + footer
}

let babel
async function loadBabel() {
  if (!babel) {
    babel = await import('@babel/core')
  }
  return babel
}
/** 给dva model 添加hot，使model可以热更新，默认给 包含 /models/ 路径的文件添加 */
function viteDvaModelRefresh() {
  return {
    name: 'vite-plugin-dva-model-refresh',
    enforce: 'pre',
    apply: 'serve',
    async transform(code, id) {
      if (id.includes('/node_modules/')) return
      if (!id.includes('/models/')) return
      const babel2 = await loadBabel()
      const result = await babel2.transformAsync(code)
      if (result) {
        let code2 = addRefreshWrapper(result.code)
        return { code: code2, map: result.map }
      }
    },
  }
}

export { viteDvaModelRefresh as default }
